﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using DotNet.DevOps.Tasks.Util;

namespace DotNet.DevOps.Tasks.AssemblyInfo.Updaters
{
    internal class CopyrightUpdater : PropertyUpdater
    {
        private Dictionary<String, String> properties;
        private Regex regex = new Regex(@"\d{4}", RegexOptions.Compiled | RegexOptions.Singleline);

        public CopyrightUpdater(AssemblyInfo asm, ILog logger)
            : base(asm, logger)
        {
        }

        protected override Dictionary<String, String> GetPropertyNameValuePairs()
        {
            return properties ?? (properties = asm.GetSpecialStringPropertyNameValuePairsByName("AssemblyCopyright"));
        }

        protected override String GetNewEntryValue(String keyName, String oldValue)
        {
            var valueToReplaceWith = ChooseValueToUse(properties[keyName], oldValue);

            if (string.IsNullOrEmpty(valueToReplaceWith) == false)
            {
                return UpdateYear(valueToReplaceWith);
            }

            return null;
        }

        private static String ChooseValueToUse(String propValue, String oldValue)
        {
            if (string.IsNullOrEmpty(propValue) == false)
                return propValue;

            if (string.IsNullOrEmpty(oldValue) == false)
                return oldValue;

            return null;
        }

        private String UpdateYear(String value)
        {
            if (asm.AutoUpdateCopyrightYear == true)
            {
                return regex.Replace(value, DateTime.Now.Year.ToString());
            }
            return value;
        }
    }
}
